<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="state.title" :width="width" @ok="handleSubmit" destroyOnClose>
    <BasicTable ref="tableRef" v-bind="getBindValue" :rowSelection="rowSelection" :rowKey="state.valueField">
      <template #tableTitle>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleAdd">新增</a-button>
        <a-dropdown v-if="checkedKeys.length > 0 && state.batchDeleteApi">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="i-ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon style="fontsize: 12px" icon="ant-design:down-outlined" />
          </a-button>
        </a-dropdown>
      </template>
    </BasicTable>
  </BasicDrawer>
  <DataGroupModal @register="registerDataGroupForm" @success="tableRef.reload()" />
</template>
<script lang="ts" setup>
  import { ref, useAttrs, unref, watch, nextTick } from "vue"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { useModal } from "/@/components/Modal"
  import { useGlobSetting } from "/@/hooks/setting"
  import { columns, searchFormSchema } from "./dataGroup.data"
  import { pageDataGroup } from "/@/api/infra/dataGroup"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { propTypes } from "/@/utils/propTypes"
  import { isFunction } from "/@/utils/is"
  import DataGroupModal from "./DataGroupModal.vue"
  import { createAsyncComponent } from "/@/utils/factory/createAsyncComponent"
  import { useSelectBiz } from "/@/components/Form/src/jeecg/hooks/useSelectBiz"
  import { Icon } from "/@/components/Icon"
  //此处需要异步加载BasicTable
  const BasicTable = createAsyncComponent(() => import("/@/components/Table/src/BasicTable.vue"), {
    loading: true,
  })

  const TableAction = createAsyncComponent(() => import("/@/components/Table/src/components/TableAction.vue"), {
    loading: true,
  })

  // 声明Emits
  const emit = defineEmits(["success", "register", "getSelectResult"])
  const attrs = useAttrs()

  interface State {
    title?: string
    /**
     * 业务类型
     * @see DataGroupBizType
     */
    bizType: string | number
    /**
     * 组类型, 根据每个业务自行定义
     */
    groupType?: string
    // 是否为树形结构, 编辑的时候会展示树
    isTree: boolean
    //api
    deleteApi: Function
    batchDeleteApi: Function
    saveOrUpdateApi: Function

    labelField: string
    valueField: string
    maxSelectCount: number
    rowType: string
    // 组编码是否为必填项
    groupCodeRequired: boolean
  }

  const state = ref<State>({
    title: "数据分组",
    isTree: false,
    labelField: "label",
    valueField: "id",
    bizType: "",
    maxSelectCount: -1,
    deleteApi: () => {},
    batchDeleteApi: () => {},
    saveOrUpdateApi: () => {},
    rowType: "radio",
    groupCodeRequired: false,
  })
  const tableRef = ref<any>()
  const width = ref("800")

  const { createMessage } = useMessage()
  const glob = useGlobSetting()
  const [registerDataGroupForm, { openModal: openDataGroupForm }] = useModal()

  const config = {
    rowKey: "id",
    api: pageDataGroup,
    beforeFetch: (params) => {
      params.bizType = state.value.bizType
    },
    showTableSetting: false,
    showIndexColumn: false,
    clickToRowSelect: false,
    bordered: false,
    striped: false,
    immediate: false,
    columns: columns,
    canResize: false,
    scroll: { x: undefined },
    formConfig: {
      schemas: searchFormSchema,
      showResetButton: false,
      fieldMapToTime: [["fieldTime", ["beginDate", "endDate"], "YYYY-MM-DD HH:mm:ss"]],
    },
    actionColumn: {
      width: 60,
      title: "操作",
      dataIndex: "action",
      fixed: "right",
      actions: (record: Recordable) => [
        {
          ifShow: state.value.deleteApi !== undefined,
          icon: "ant-design:delete-outlined",
          color: "error",
          disabled: record.code === "default",
          popConfirm: {
            title: "是否确认删除",
            confirm: handleDelete.bind(null, record),
          },
        },
        {
          icon: "ant-design:edit-outlined",
          disabled: record.code === "default",
          onClick: handleEdit.bind(null, record),
          // ifShow: record.sendStatus == 0
        },
      ],
    },
  }

  const getBindValue = Object.assign({}, unref(attrs), config)

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    state.value = Object.assign({ ...data }, unref(attrs))
    state.value.maxSelectCount = Number(state.value.maxSelectCount || -1)
    width.value = data.width || width.value

    setDrawerProps({ confirmLoading: false })
  })

  watch(
    () => tableRef.value,
    (val: any) => {
      tableRef.value && nextTick(() => tableRef.value.reload())
    }
  )

  const getIsRadioSelection = () => {
    const maxSelectCount = Number(unref(attrs)?.maxSelectCount || -1)
    return maxSelectCount !== -1 && maxSelectCount === 1 ? true : false
  }
  async function handleSubmit() {
    try {
      getSelectResult((options, values) => {
        //回传选项和已选择的值
        emit("getSelectResult", options, unref(values))
        emit("success")
        //关闭弹窗
        closeDrawer()
      })
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }

  const [{ rowSelection, checkedKeys, getSelectResult, selectRows }] = useSelectBiz(pageDataGroup, {
    ...getBindValue,
    isRadioSelection: getIsRadioSelection(),
    params: { bizType: getBindValue.bizType },
  })

  /**
   * 新增事件
   */
  function handleAdd() {
    openDataGroupForm(true, {
      isUpdate: false,
      ...state.value,
    })
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    console.log("delete record", record)

    if (isFunction(state.value.deleteApi)) {
      await state.value.deleteApi({ id: record.id, name: record.name }, () => {
        tableRef.value.reload()
        createMessage.success("删除成功")
      })
      return
    }
    console.error("state.deleteApi is not function")
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    console.log("batch selectRows", selectRows.value)

    if (isFunction(state.value.batchDeleteApi)) {
      await state.value.batchDeleteApi({ ids: selectRows.value.map((e) => e["id"]) }, () => {
        tableRef.value.reload()
        createMessage.success("删除成功")
      })
      return
    }
    console.error("state.batchDeleteApi is not function")
  }

  const handleEdit = (record) => {
    openDataGroupForm(true, {
      isUpdate: true,
      record,
      ...state.value,
    })
  }
</script>
